package com.shujia.spark.core

import org.apache.spark.rdd.RDD
import org.apache.spark.{SparkConf, SparkContext}

object Demo11Join {
  def main(args: Array[String]): Unit = {
    val conf = new SparkConf()
    conf.setAppName("map")
    conf.setMaster("local")

    val sc = new SparkContext(conf)

    //基于集合构建一个rdd,用于测试
    val nameRDD: RDD[(String, String)] = sc.parallelize(
      List(
        ("001", "张三"),
        ("002", "李四"),
        ("003", "王五"),
        ("004", "赵六")
      ))

    val ageRDD: RDD[(String, Int)] = sc.parallelize(
      List(
        ("000", 22),
        ("001", 23),
        ("002", 24),
        ("003", 25)
      ))

    /**
     * inner join :内关联，两边都有才能关联上
     *
     */

    val innerJoinRDD: RDD[(String, (String, Int))] = nameRDD.join(ageRDD)

    //整理数据
    innerJoinRDD
      .map {
        case (id: String, (name: String, age: Int)) =>
          (id, name, age)
      }
      .foreach(println)


    /**
     * left join :左关联，以左表为基础，如果右表没有数据，补null
     *
     * Option: 两个取值，有值或者None, 如果没有关联上，就是None
     *
     */

    val leftJoinRDD: RDD[(String, (String, Option[Int]))] = nameRDD.leftOuterJoin(ageRDD)

    //整理数据
    leftJoinRDD
      .map {
        //关联上的情况
        case (id: String, (name: String, Some(age))) =>
          (id, name, age)

        //没有关联上的处理方式
        case (id: String, (name: String, None)) =>
          (id, name, 0)
      }
      .foreach(println)


    /**
     * full join : 全关联，只要有一边有数据就会出结果，如果另一边没有，补null
     *
     */

    val fullJoinRDD: RDD[(String, (Option[String], Option[Int]))] = nameRDD.fullOuterJoin(ageRDD)


    //整理数据
    fullJoinRDD
      .map {
        case (id: String, (Some(name), Some(age))) =>
          (id, name, age)

        case (id: String, (Some(name), None)) =>
          (id, name, 0)

        case (id: String, (None, Some(age))) =>
          (id, "默认值", age)
      }
      .foreach(println)

  }

}
